package com.tongzhou.client;

import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import com.tongzhou.db.exception.DBException;
import com.tongzhou.tongzhou.account.dao.IAccountDAO;
import com.tongzhou.tongzhou.account.dao.impl.AccountDAO;
import com.tongzhou.tongzhou.account.model.Account;
import com.tongzhou.util.Util;

//登陆接口
public class ClientLogin {
	IAccountDAO dao=new AccountDAO();
	Account account=null;
	public String getInfo(String json,HttpServletResponse response){
		JSONObject jsonObject = JSONObject.fromObject( json );
		String companyName=null;
		String company_num=null;
		if(jsonObject.get("companyName")!=null){
			companyName=(String) jsonObject.get("companyName");
		}
		if(jsonObject.get("companyNum")!=null){
			company_num=(String) jsonObject.get("companyNum");
		}
		account=new Account();
		try {
			account.setCompany_name(companyName);
			account.setCompany_num(company_num);
			List<Account> result=dao.checkLoginInfo(account);
			StringBuffer str=new StringBuffer();
			if(result.size()>=1){
				account=result.get(0);
				str.append("{'success':1,'msg':{'companyName':'"+account.getCompany_name()+"',");
				str.append("'companyNum':'"+account.getCompany_num()+"',");
				str.append("'rid':"+Util.changeToObj(String.valueOf(account.getRid()))+",");
				str.append("'highRisk':"+Util.changeToObj(String.valueOf(account.getHigh_risk()))+",");
				str.append("'offerType':"+Util.changeToObj(String.valueOf(account.getOffer_type()))+",");
				str.append("'offerCall':'"+Util.changeToObj(account.getOffer_call())+"'}}");
			}else{
				try {
//					companyName="佛山市南海中艺联发彩印包装厂";
//					company_num="ZYLF01";
					response.sendRedirect("http://www.tongzhoudg.com/tongzhouClient/client.do?method=1&json={'companyName':'"+URLEncoder.encode(new String(companyName), "utf-8")+"','companyNum':'"+company_num+"'}");
				} catch (Exception e) {
					e.printStackTrace();
				}
				str.append("{'success':0,'msg':'没有对应的客户!'}");
			}
//			return str.toString();
		} catch (DBException e) {
			e.printStackTrace();
		}
//		String str="{'success':1,'msg':{'companyName':'同舟有限公司','companyNum':'CODE-001',";
//		str+="'rid':33,'highRisk':1,'offerType':1,'offerCall':'18938037662'}}";
//		return str;
		return "{'success':0,'msg':'输入参数有误!'}";
	}
	public static String InputStreamtoString(InputStream in) throws IOException {
		StringBuffer out = new StringBuffer();
		
		byte[] buffer = new byte[1024];
		
		for (int i; (i = in.read(buffer)) != -1;) 
		{
			out.append(new String(buffer, 0, i));
		}
		
		return out.toString();
	}
}
